package com.zlyx.easy.http.handlers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

import com.zlyx.easy.core.utils.SpringUtils;
import com.zlyx.easy.http.models.RequestModel;

/**
 * 
 * @Auth 赵光
 * @Describle
 * @2019年12月25日
 */
public abstract class AbstractMappingHandler {

	@Autowired
	protected RestTemplate restTemplate;

	/**
	 * 转发业务
	 * 
	 * @param beanName
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public static Object call(RequestModel rm) throws Exception {
		return SpringUtils.<AbstractMappingHandler>getBean(rm.getMethod()).doHandle(rm);
	}

	public Object doHandle(RequestModel requestModel) throws Exception {
		String[] urls = requestModel.getUrls();
		if (urls.length > 1) {
			for (String url : urls) {
				handleMapping(url, requestModel);
			}
			return null;
		}
		return handleMapping(urls[0], requestModel);
	}

	public abstract Object handleMapping(String url, RequestModel requestModel);

	public String handleIpAndPort(String url, RequestModel rm) {
		if (url.contains(":ip")) {
			url = url.replaceAll(":ip", rm.getIp());
		} else if (url.contains("{ip}")) {
			url = url.replaceAll("{ip}}", rm.getIp());
		}
		if (url.contains(":port")) {
			url = url.replaceAll(":port", "" + rm.getPort());
		} else if (url.contains("{port}")) {
			url = url.replaceAll("{port}}", "" + rm.getPort());
		}
		return url;
	}

}